#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QScreen>
#include <QDebug>
#include <QCommandLineParser>
#include <QTimer>
#include <QtWidgets>

MainWindow::MainWindow(const QString& targetScreenName, int splitCount, QString& bkImagePath, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags() | Qt::Tool);
    // 设置黑色背景
    setStyleSheet("background-color: black;");

    // 获取目标屏幕
    QScreen *targetScreen = nullptr;
    if (!targetScreenName.isEmpty()) {
        for (QScreen *screen : QGuiApplication::screens()) {
            if (screen->name() == targetScreenName) {
                targetScreen = screen;
                break;
            }
        }
    }

    if (!targetScreen) {
        targetScreen = QGuiApplication::primaryScreen();
        if (targetScreenName.isEmpty()) {
            QLabel *errorLabel = new QLabel("未获取到屏幕名称参数,请传参", this);
            errorLabel->setAlignment(Qt::AlignCenter);
            errorLabel->setStyleSheet("color: red; font-size: 24px;");
            setCentralWidget(errorLabel);
        } else {
            QLabel *errorLabel = new QLabel(QString("未找到名称为%1的屏幕，请检查传参是否正确").arg(targetScreenName), this);
            errorLabel->setAlignment(Qt::AlignCenter);
            errorLabel->setStyleSheet("color: red; font-size: 24px;");
            setCentralWidget(errorLabel);
        }
        return;
    }

    // 设置窗口到目标屏幕
    setGeometry(targetScreen->geometry());

    // 创建显示区域
    centralWidget = new QWidget(this);
    gridLayout = new QGridLayout(centralWidget);
    setCentralWidget(centralWidget);

    int rows, cols;
    if (splitCount == 1) {
        rows = 1;
        cols = 1;
    } else if (splitCount == 4) {
        rows = 2;
        cols = 2;
    } else if (splitCount == 6) {
        rows = 2;
        cols = 3;
    } else if (splitCount == 9) {
        rows = 3;
        cols = 3;
    }

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            
            QLabel *label = new QLabel(centralWidget);
            label->setAlignment(Qt::AlignCenter);
            gridLayout->addWidget(label, i, j);
            displayLabels.append(label);
            if(!bkImagePath.isEmpty()){
                // QPixmap pixmap;
                // if (pixmap.load(bkImagePath)) {
                //     // 设置布局属性
                //     label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
                //     // 设置label的边距为0
                //     label->setContentsMargins(0, 0, 0, 0);
                //     //label->setScaledContents(true);  // 关键属性：自动缩放内容
                //     // 让图片在label中自适应大小显示，去除保持宽高比和光滑变换
                //     label->setPixmap(pixmap.scaled(label->size(), Qt::IgnoreAspectRatio, Qt::FastTransformation));
                    
                //     label->setStyleSheet("QLabel { background-color: transparent; }");
                //     // 强制立即应用布局
                //     //label->adjustSize();
                //     //QCoreApplication::processEvents();
                // } else if (bkImagePath.endsWith(".jpg") || bkImagePath.endsWith(".png")) {
                //     label->setText("图片不可读(jpg/png)");
                //     label->setStyleSheet("color: red; font-size: 24px;");
                // }else {
                //     label->setText("图片不可读");
                //     label->setStyleSheet("color: red; font-size: 24px;");
                // }
                QPixmap pixmap(bkImagePath);
                if (!pixmap.isNull()) {
                    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
                    label->setContentsMargins(0, 0, 0, 0);
                    gridLayout->addWidget(label, i, j);

                    // 延迟缩放至布局完成
                    QTimer::singleShot(0, label, [label, pixmap]() {
                        QSize targetSize = label->size();
                        if (targetSize.isEmpty()) targetSize = QSize(100, 100); // 防止初始尺寸为0
                        label->setPixmap(pixmap.scaled(
                            targetSize, 
                            Qt::IgnoreAspectRatio, 
                            (pixmap.width() < targetSize.width()) 
                                ? Qt::SmoothTransformation 
                                : Qt::FastTransformation
                        ));
                    });
                }else {
                        label->setText("图片不可读");
                        label->setStyleSheet("color: red; font-size: 24px;");
                    }
            }else{
                label->setText("智林白板");
                label->setStyleSheet("color: white; font-size: 24px;");
            }
        }
    }

    // 启动UDS服务器
    localServer = new QLocalServer(this);
    if (localServer->listen("com.zltongxue.screenSplitAssist")) {
        connect(localServer, &QLocalServer::newConnection, this, &MainWindow::newConnection);
    } else {
        qDebug() << "Failed to start UDS server:" << localServer->errorString();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newConnection()
{
    QLocalSocket *socket = localServer->nextPendingConnection();
    connect(socket, &QLocalSocket::readyRead, this, &MainWindow::readData);
    connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
}

void MainWindow::readData()
{
    QLocalSocket *socket = qobject_cast<QLocalSocket*>(sender());
    if (!socket) return;

    QByteArray data = socket->readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    if (jsonDoc.isArray()) {
        QJsonArray jsonArray = jsonDoc.array();
        for (const QJsonValue &value : jsonArray) {
            if (value.isObject()) {
                QJsonObject obj = value.toObject();
                int zoneIndex = obj["zoneIndex"].toInt() - 1;
                QString imageUri = obj["imageUri"].toString();

                if (zoneIndex >= 0 && zoneIndex < displayLabels.size()) {
                    QLabel *label = displayLabels[zoneIndex];
                    QPixmap pixmap;
                    if (pixmap.load(imageUri)) {
                        // 设置label的边距为0
                        label->setContentsMargins(0, 0, 0, 0);
                        // 让图片在label中自适应大小显示，去除保持宽高比和光滑变换
                        label->setPixmap(pixmap.scaled(label->size(), Qt::IgnoreAspectRatio, Qt::FastTransformation));
                    } else {
                        label->setText("图片不可读");
                        label->setStyleSheet("color: red; font-size: 24px;");
                    }
                }
            }
        }
    }
}
